const WebSocket = require('ws');
const DateModule = require('../../database/user')


// const find = DateModule.userModule.find()
// console.log(find)


// 全局存储所有在线用户和群组
const connections = new Map(); // { userId: WebSocket }
const groups = new Map();      // { groupId: Set<userId> }

function attachWebSocket(server) {
    const wss = new WebSocket.Server({ server });


    wss.on('connection', (ws) => {
        console.log('新的链接');

        ws.on('message',async (data) => {
            let msg;

            try {
                msg = JSON.parse(data);
                console.log(msg)
            } catch (e) {
                ws.send(JSON.stringify({ type: 'error', message: 'Invalid JSON' }));
                return;
            }

            // 处理暂存消息
            if (msg.type==='Preive'){
                connections.set(msg.userId, ws);
                const find =await DateModule.MessageModel.find({userId:msg.userId})
                const memberSocket = connections.get(msg.userId);
                memberSocket.send(JSON.stringify(find))
            }

            // 登录时，查所有用户，加入群聊1
            if (msg.type === 'login') {
                try {
                    const users = await DateModule.userqModel.find({});
                    const groupSet = new Set();
                    users.forEach(user => {
                        groupSet.add(user._id.toString());
                    });
                    groups.set('群聊1', groupSet);
                    console.log('群聊1成员:', Array.from(groupSet));
                } catch (err) {
                    console.error('查询用户失败:', err);
                }
            }

            if (msg.typeA && msg.typeB && msg.typeC && msg.content) {
                // 群聊消息结构
                const groupId = '群聊1';
                const members = groups.get(groupId);
                if (!members) {
                    console.log('群聊不存在');
                    return;
                }
                DateModule.PushModel.create(msg)
                members.forEach(userId => {
                    if (connections.has(userId)) {
                        console.log(`用户${userId}在线`);
                        const memberSocket = connections.get(userId);
                        memberSocket.send(JSON.stringify(msg));
                    } else {
                        console.log(`用户${userId}不在线`);
                        DateModule.MessageModel.create({userId:userId,desc:msg.content,time:Date.now()})
                    }
                });
            }

            if (msg.type === "joinGroup") {
                if (!groups.has(msg.groupId)) {
                    groups.set(msg.groupId, new Set());
                }
                groups.get(msg.groupId).add(msg.userId);
                console.log(groups)
                console.log(`用户${msg.userId}加入群${msg.groupId}`);
            }

            // 群聊
            if (msg.type === 'group') {
                const members = groups.get(msg.targetId);
                members?.forEach(userId => {
                    console.log(userId, groups);
                    const memberSocket = connections.get(userId); // 查 connections
                    console.log(memberSocket);
                    if (memberSocket && memberSocket.readyState === WebSocket.OPEN) {
                        memberSocket.send(JSON.stringify(msg));
                    }
                });
            }
        });

        ws.on('error', (err) => {
            console.error('WebSocket 错误:', err);
            ws.close();
        });

        ws.on('close', (code, reason) => {
            console.log(`用户断开连接，代码: ${code}, 原因: ${reason}`);
        });
    });

    // 广播，给所有用户发送消息
    function broadcast(msg) {
        wss.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(msg);
            }
        });
    }

    console.log('WebSocket服务已绑定到HTTP服务器');
}


module.exports = attachWebSocket;